package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;
  


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public String uploadBpmnInfo(MultipartFile file) throws IOException {

        // 获取文件的扩扎明
        String ext = FileUploadUtils.getExtension(file);
        if(!"bpmn".equals(ext)){
            throw new BusinessException("请上传bpmn文件");
        }
        // 把文件保存服务器的磁盘当中
        String path = FileUploadUtils.upload(SystemConfig.getProfile(), file);
        return path;
    }

    @Override
    public void deploy(String path, String info, String bpmnType) throws IOException {
        // 1 根据path 最终找到文件
        File file = new File(SystemConfig.getProfile(),path);
        FileInputStream fileInputStream = new FileInputStream(file);
        // 2 通过activiti 的api 把流程文件部署起来
        Deployment deployment = repositoryService.
                createDeployment().
                addInputStream(path, fileInputStream).
                deploy();

        fileInputStream.close();
        // 查询流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
        // 3 把信息最终保存一份到BpmnInfo当中
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setInfo(info);
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setDeployTime(deployment.getDeploymentTime());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        //1 删除bpmnInfo 信息
        bpmnInfoMapper.deleteByPrimaryKey(id);
        // TODO: 考虑到服务单项状态问题
        //2 删除acitiviti当中信息
        ProcessDefinition processDefinition = repositoryService.
                createProcessDefinitionQuery().
                deploymentId(bpmnInfo.getDeploymentId()).singleResult();
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId());
        //3 删除文件
        File file = new File(SystemConfig.getProfile(),processDefinition.getResourceName());
        if(file.exists()){
            file.delete();
        }
    }

    @Override
    public InputStream readResource(Long deploymentId, String type) {
        InputStream inputStream  = null;
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId.toString()).singleResult();
        if("xml".equals(type)){
            // 响应xml文件
            inputStream = repositoryService.getResourceAsStream(deploymentId.toString(),processDefinition.getResourceName());
        }else{
            // 响应一个png
            DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
            /**
             * bpmnModel : model 石油我们流程图节点信息
             * 第二个参数: 高亮节点集合
             * 第三个参数: 高亮连线集合
             *
             */
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            inputStream = defaultProcessDiagramGenerator.generateDiagram(bpmnModel,
                    Collections.emptyList(),
                    Collections.emptyList(),
                    "宋体",
                    "宋体",
                    "宋体");
        }

        return inputStream;
    }

    @Override
    public List<BpmnInfo> queryByType(String type) {

        return bpmnInfoMapper.queryByType(type);
    }


}
